package com.zmx.patientend.fragment.order;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.OrderManagementAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.OrderInfo;
import com.zmx.patientend.pojo.OrderProduct;
import com.zmx.patientend.pojo.Paging;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.activity.GoodsOrderDetailsActivity;
import com.zmx.patientend.view.util.CustomToast;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 程序猿：胖胖祥
 * 时 间：2020/12/25  12:28
 * 功 能：待支付
 */
public class ToBePaidOrderFragment extends Fragment implements OrderManagementAdapter.PayOnListener{



    private OrderManagementAdapter adapter;
    private List<OrderInfo> lists;
    private RecyclerView recyclerView;

    private ImageView empty_image;

    private Integer listPosition;


    private Paging paging = new Paging();
    private SmartRefreshLayout refreshLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_orders, container, false);


        lists = new ArrayList<>();
        recyclerView = view.findViewById(R.id.recyclerView);
        adapter = new OrderManagementAdapter(this.getActivity());
        adapter.setPayOnListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(ToBePaidOrderFragment.this.getContext()));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent();
                intent.putExtra("orderNumber", lists.get(listPosition).getId() + "");
                intent.putExtra("state", lists.get(listPosition).getState() + "");
                intent.setClass(ToBePaidOrderFragment.this.getContext(), GoodsOrderDetailsActivity.class);
                startActivity(intent);

            }
        });
        empty_image = view.findViewById(R.id.empty_image);

        // 开启自动加载功能
        refreshLayout = view.findViewById(R.id.refreshLayout); //触发自动刷新
        refreshLayout.autoRefresh();
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {

            lists.clear();
            paging.setPageNow(1);
            getOrderList();

        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            if (paging.getPageNow() < paging.getPageCount()) {

                paging.setPageNow(paging.getPageNow() + 1);
                getOrderList();

            } else {

                refreshLayout.finishLoadMore(true);
                CustomToast.getInstance().showToastCustom(ToBePaidOrderFragment.this.getContext(), "没有更多数据啦!", Gravity.BOTTOM);

            }

        });


        return view;

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:

                    try {

                        if (paging.getPageNow() == 1){
                            lists.clear();
                        }

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1){

                            empty_image.setVisibility(View.GONE);
                            JSONArray data = object.getJSONArray("data"); paging.setPageCount(object.getInt("count"));
                            Gson gson = new Gson();
                            for (int i = 0;i<data.length();i++){

                                OrderInfo oi = gson.fromJson(data.getJSONObject(i).toString(),OrderInfo.class);

                                JSONArray detailed = new JSONArray(data.getJSONObject(i).getString("detailed"));
                                List<OrderProduct> ops = new ArrayList<>();
                                for (int j=0;j<detailed.length();j++){

                                    OrderProduct op = gson.fromJson(detailed.getJSONObject(j).toString(),OrderProduct.class);
                                    ops.add(op);

                                }

                                oi.setLists(ops);
                                lists.add(oi);


                            }



                        }else{

                            empty_image.setVisibility(View.VISIBLE);

                        }

                        adapter.setListAndNotifyDataSetChanged(lists);
                        if (paging.getPageNow() == 1) {

                            refreshLayout.finishRefresh(true);

                        } else {

                            refreshLayout.finishLoadMore(true);

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("异常","异常"+e.toString());
                    }

                    break;
                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray data = object.getJSONArray("data");
                        for (int i=0;i<data.length();i++){

                            if (data.getJSONObject(i).getInt("id") == 1){

                                balance = new BigDecimal(data.getJSONObject(i).getString("moeny"));
                                pay_meney = data.getJSONObject(i).getInt("status");

                            }
                            if (data.getJSONObject(i).getInt("id") == 2){

                                pay_wex = data.getJSONObject(i).getInt("status");

                            }
                            if (data.getJSONObject(i).getInt("id") == 3){

                                pay_al = data.getJSONObject(i).getInt("status");

                            }

                        }

                        pop_up(balance);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        CustomToast.getInstance().showToastCustom(ToBePaidOrderFragment.this.getContext(), object.getString("msg"), Gravity.BOTTOM);

                        if (object.getInt("code") == 1){

                            paging.setPageNow(1);
                            getOrderList();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }

        }
    };

    public void getOrderList() {

        List<String> ls = new ArrayList<>();
        ls.add(paging.getPageSize() + "");
        ls.add(paging.getPageNow() + "");
        ls.add("3");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(ToBePaidOrderFragment.this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(ToBePaidOrderFragment.this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getOrderList");
        params.put("data[state]", "3");
        params.put("data[row]", paging.getPageNow());
        params.put("data[number]", paging.getPageSize());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 1, 404);


    }

    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();
        requestparams.append(MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();

    }

    @Override
    public void setPayOnListener(int listPosition) {

        this.listPosition = listPosition;
        getPays();

    }

    @Override
    public void setCancelOrder(int listPosition) {

        this.listPosition = listPosition;
        new AlertDialog.Builder(this.getContext()).setTitle("确认取消吗？")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("确定取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        // 点击“确认”后的操作
                        closeOrder(lists.get(listPosition).getId()+"");

                    }
                })
                .setNegativeButton("再想想", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击“返回”后的操作,这里不设置没有任何操作
                    }
                }).show();

    }

    public void closeOrder(String orderNumber) {

        List<String> ls = new ArrayList<>();
        ls.add(orderNumber);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "closeOrder");
        params.put("data[order_id]", orderNumber);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 3, 404);

    }

    private Integer pay_meney=0,pay_wex=0,pay_al=0;
    private BigDecimal balance;//钱包余额
    //弹出支付界面
    private Dialog modify_dialogs;//弹出框
    boolean balan = false;//判断余额是否够支付
    private Integer pay = 0;//支付方式1为余额。2为微信，3为支付宝

    public void pop_up(BigDecimal balance) {

        View view;//选择性别的view

        modify_dialogs = new Dialog(this.getContext(), R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        view = LayoutInflater.from(this.getContext()).inflate(R.layout.dialog_pay_choose, null);

        //将布局设置给Dialog
        modify_dialogs.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = modify_dialogs.getWindow();

        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //        lp.y = 20;//设置Dialog距离底部的距离

        //// 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        modify_dialogs.onWindowAttributesChanged(lp);
        //       将属性设置给窗体
        modify_dialogs.setCanceledOnTouchOutside(false);
        modify_dialogs.show();//显示对话框

        TextView money = view.findViewById(R.id.money);
        money.setText("￥"+lists.get(listPosition).getTotal());

        ImageView wx_image,zfb_image,balance_image;
        wx_image = view.findViewById(R.id.wx_image);
        zfb_image = view.findViewById(R.id.zfb_image);
        balance_image = view.findViewById(R.id.balance_image);
        RelativeLayout wx_layout,zfb_layout,balance_layout;
        balance_layout = view.findViewById(R.id.balance_layout);
        if (pay_meney == 1){
            balance_layout.setVisibility(View.GONE);
        }
        balance_layout.setOnClickListener(v -> {

            //判断余额是否足够
            if(balan){

                pay = 1;
                balance_image.setVisibility(View.VISIBLE);
                wx_image.setVisibility(View.GONE);
                zfb_image.setVisibility(View.GONE);

            }else{

                CustomToast.getInstance().showToastCustom(ToBePaidOrderFragment.this.getContext(), "余额不足本次支付!", Gravity.BOTTOM);


            }


        });

        zfb_layout = view.findViewById(R.id.zfb_layout);
        if (pay_al == 1){
            zfb_layout.setVisibility(View.GONE);
        }
        zfb_layout.setOnClickListener(v -> {
            pay = 2;
            balance_image.setVisibility(View.GONE);
            wx_image.setVisibility(View.GONE);
            zfb_image.setVisibility(View.VISIBLE);
        });
        wx_layout = view.findViewById(R.id.wx_layout);
        if (pay_wex == 1){
            wx_layout.setVisibility(View.GONE);
        }
        wx_layout.setOnClickListener(v -> {
            pay = 3;
            balance_image.setVisibility(View.GONE);
            wx_image.setVisibility(View.VISIBLE);
            zfb_image.setVisibility(View.GONE);
        });

        TextView balance_text = view.findViewById(R.id.balance_text);
        if (balance.compareTo(new BigDecimal(lists.get(listPosition).getTotal())) >=0 ){

            balance_text.setText(Html.fromHtml("账号余额 <font color='#FF0000'>"+ balance+"</font>"));
            balan = true;

        }else{

            balan = false;
            balance_text.setText(Html.fromHtml("账号余额 <font color='#FF0000'>"+ balance+"</font>（余额不足）"));

        }
        ImageView close = view.findViewById(R.id.close);
        close.setOnClickListener(v -> modify_dialogs.dismiss());



        Button button = view.findViewById(R.id.pay);
        button.setOnClickListener(v -> {

            if(pay == 0){

                CustomToast.getInstance().showToastCustom(ToBePaidOrderFragment.this.getContext(), "请选择支付方式!", Gravity.BOTTOM);

            }else{

                //先判断点击了哪种支付类型
                if(pay == 1){

                    if(balan){
                        payOrder(lists.get(listPosition).getId()+"");
                        modify_dialogs.dismiss();

                    }

                }
            }
        });

    }

    public void payOrder(String orderNumber){

        List<String> ls = new ArrayList<>();
        ls.add(orderNumber);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "payOrder");
        params.put("data[order_id]", orderNumber);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 3, 404);

    }
    public void getPays() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getPays");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 2, 404);


    }

    protected boolean isCreated = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 标记
        isCreated = true;
    }

    /**
     * 此方法目前仅适用于标示ViewPager中的Fragment是否真实可见
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (!isCreated) {
            return;
        }

        if (isVisibleToUser) {

            paging.setPageNow(1);
            getOrderList();
        }
    }
}